<script setup lang="ts">
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { IcEdit } from '@vben/icons';

import {
  DeleteOutlined,
  EditOutlined,
  InfoCircleOutlined,
  LinkOutlined,
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';
import { storeToRefs } from 'pinia';

import {
  douying,
  errimage,
  kuaisou,
  pingduoduo,
  taobao,
  xiaohonshu,
} from '#/base';
import { doudianStore, in1688ToDoudianStore } from '#/store/modules';

import AiTitle from './aiTitle.vue';
import EditModalContent from './editModalContent.vue';
import { getStrLen } from './tools';
// const props = defineProps<{
//   item: any;
// }>();
// const item = computed(() => props.item);
const item: any = defineModel();
// const emit = defineEmits(['removeItem']);
const [Modals, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: EditModalContent,
});

// const item = computed(props.item);
// console.log('item', item.value);
// provide('editDetailItem', [item]);

const doudianStoreModel = doudianStore();

const in1688ToDoudian = in1688ToDoudianStore();

const { nowSelectGood } = storeToRefs(in1688ToDoudian);

const DoudianCategoryList = computed(
  () => doudianStoreModel.DoudianCategoryList,
);
// const selectCategory = computed(() => {
//   if (item.value.categoryIds && item.value.categoryIds.length > 0) {
//     return item.value.categoryIds.map((category: any) => {
//       return category.name;
//     });
//   }
//   return [];
// });
const on1688Category = computed(() => {
  if (item.value.categoryId1688s && item.value.categoryId1688s.length > 0) {
    return item.value.categoryId1688s
      .map((category: any) => {
        return category.name;
      })
      .join(' > ');
  }
  return '';
});
// const value = ref<string[]>(selectCategory.value);
// const checked = ref<boolean>(false);
const fieldNames = {
  label: 'name',
  value: 'id',
  children: 'children',
};
function removeSelectItem() {
  Modal.confirm({
    title: '提示',
    content: '确定删除选中的商品吗？',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      in1688ToDoudian.removeItemFunc(item.value);
    },
  });
}

function openModal() {
  // in1688ToDoudian.setSelectGood(item.value.offerId);
  nowSelectGood.value = item.value.offerId;
  // in1688ToDoudian.$patch({
  //   nowSelectGood: item.value.offerId,
  // });
  modalApi.open();
}
function editItem() {
  if (!cheackdedItem()) return;
  openModal();
}
function cheackdedItem() {
  if (!item.value.categoryIdsOps || item.value.categoryIdsOps.length === 0) {
    Modal.confirm({
      title: '提示',
      content: '请选择商品类目',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        return false;
      },
    });
    return false;
  }
  item.value.categoryId =
    item.value.categoryIds[item.value.categoryIds.length - 1].id;
  return true;
}

function dropChange(status: boolean) {
  if (!status) {
    // in1688ToDoudian.getItemDetail(item.value.offerId);
    const outerId =
      item.value.categoryIdsOps[item.value.categoryIdsOps.length - 1];
    // eslint-disable-next-line unicorn/prefer-number-properties
    if (isNaN(outerId)) return;
    if (item.value.categoryId !== outerId) {
      item.value.categoryId = outerId;

      in1688ToDoudian.getItemDetail(item.value.offerId);
    }
  }
}
const aiTitleBoxState = ref(false);
const getTitleLodinStatus = ref(false);
const selectImage = ref();

function getAiTitle() {
  aiTitleBoxState.value = true;

  selectImage.value = item.value.mainPicList[0];
}
function getSelectAiTitle(title: string) {
  if (!title) {
    return message.error('请选择标题！！！');
  }
  aiTitleBoxState.value = false;
  item.value.goodsTitle = title;
  message.success('标题已替换');
}

const getPrice = computed(() => {
  if (!item.value || !item.value.specPricesV2) return '';
  const maxPrice = Math.max(
    ...item.value.specPricesV2.map((item: any) => item.price),
  );
  const minPrice = Math.min(
    ...item.value.specPricesV2.map((item: any) => item.price),
  );
  if (minPrice === maxPrice) {
    return minPrice;
  }
  return `${minPrice}~${maxPrice}`;
});
</script>

<template>
  <div v-if="item" class="mb-4 border-b pb-2">
    <a-spin
      :spinning="item.isLodin"
      class="mx-auto my-auto h-full w-full"
      size="large"
    >
      <div class="flex w-full items-start justify-start">
        <a-image
          :fallback="errimage"
          :src="item.mainPicList[0]"
          :width="100"
          class="rounded border"
        />
        <div class="ml-4 flex-1">
          <a-form :self-update="true">
            <a-form-item
              :help="item.goodsTitle ? '' : '请填写商品标题'"
              :validate-status="item.goodsTitle ? 'success' : 'error'"
              class="mb-1"
              label="商品标题"
            >
              <div class="flex w-full items-center justify-between">
                <a-input
                  v-if="item.rule"
                  v-model:value="item.goodsTitle"
                  :placeholder="`请输入${item.rule.recommendNameRule?.titleLimitRule?.minLength}-${item.rule.recommendNameRule?.titleLimitRule?.maxLength}个字符`"
                  style="flex: 1"
                >
                  <template #suffix>
                    <span>
                      {{ getStrLen(item.goodsTitle || '') }}/
                      {{
                        item.rule.recommendNameRule?.titleLimitRule?.maxLength
                      }}
                    </span>
                  </template>
                </a-input>
                <a-input
                  v-else
                  v-model:value="item.goodsTitle"
                  class="w-full"
                  placeholder="请输入标题"
                  style="flex: 1"
                >
                  <template #suffix>
                    <span>
                      {{ getStrLen(item.goodsTitle || '') }}/
                      {{ 60 }}
                    </span>
                  </template>
                </a-input>
                <a-button
                  :loading="getTitleLodinStatus"
                  style="margin-left: 10px"
                  type="primary"
                  @click="getAiTitle"
                >
                  AI标题
                </a-button>
              </div>
            </a-form-item>
            <a-form-item
              :extra="on1688Category ? `1688类目: ${on1688Category}` : null"
              :help="
                item.categoryIdsOps && item.categoryIdsOps.length > 0
                  ? ''
                  : '请填写选择类目'
              "
              :validate-status="
                item.categoryIdsOps && item.categoryIdsOps.length > 0
                  ? 'success'
                  : 'error'
              "
              class="mb-1"
              label="商品类目"
            >
              <a-cascader
                v-model:value="item.categoryIdsOps"
                :field-names="fieldNames"
                :load-data="doudianStoreModel.loadData"
                :options="DoudianCategoryList"
                change-on-select
                placeholder="请选择类目"
                show-search
                @dropdown-visible-change="dropChange"
              >
                <template #displayRender="{ labels }">
                  <span v-for="(label, index) in labels" :key="index">
                    {{ label }}
                    <span v-if="index + 1 < labels.length"> > </span>
                  </span>
                  <span v-if="labels.length === 0">请选择类目</span>
                </template>
              </a-cascader>
            </a-form-item>
            <a-space align="center" class="w-full">
              <a-form-item class="mb-1" label="售卖价格">
                <a-space>
                  <div>￥{{ getPrice }}</div>
                  <a-button type="link" @click="editItem">
                    <template #icon>
                      <IcEdit />
                    </template>
                  </a-button>
                </a-space>
              </a-form-item>
              <a-form-item class="mb-1" label="供货价">
                <a-space>
                  <div class="w-40">￥{{ item.priceget }}</div>
                </a-space>
              </a-form-item>
              <a-form-item class="mb-1 mr-2">
                <a-tooltip
                  :title="`https://detail.1688.com/offer/${item.offerId}.html`"
                >
                  <a
                    :href="`https://detail.1688.com/offer/${item.offerId}.html`"
                    target="_blank"
                  >
                    <LinkOutlined />货源链接
                  </a>
                </a-tooltip>
              </a-form-item>
              <a-form-item
                v-if="item.supportChannels?.length > 0"
                class="mb-1"
                label="支持密文"
              >
                <div class="flex items-center">
                  <template v-for="items in item.supportChannels" :key="items">
                    <img
                      v-if="items === 'taobao'"
                      :src="taobao"
                      class="mr-1 w-6"
                    />
                    <img
                      v-if="items === 'pinduoduo'"
                      :src="pingduoduo"
                      class="mr-1 w-6"
                    />
                    <img
                      v-if="items === 'xiaohongshu'"
                      :src="xiaohonshu"
                      class="mr-1 w-6"
                    />
                    <img
                      v-if="items === 'douyin'"
                      :src="douying"
                      class="mr-1 w-6"
                    />
                    <img
                      v-if="items === 'kuaishou'"
                      :src="kuaisou"
                      class="mr-1 w-6"
                    />
                  </template>
                </div>
              </a-form-item>
              <a-popover
                v-if="item.errAlls?.errNum > 0"
                placement="bottomLeft"
                title="必填未填写"
              >
                <template #content>
                  <div
                    v-for="(items, indexs) in item.errAlls.errList"
                    :key="indexs"
                  >
                    <span class="text-red-500">*</span> {{ indexs + 1 }}:
                    {{ items.msg }}
                  </div>
                </template>
                <a-tag
                  class="ml-4 cursor-pointer"
                  color="red"
                  @click="editItem"
                >
                  {{ item.errAlls.errNum }}错误 <InfoCircleOutlined />
                </a-tag>
              </a-popover>
            </a-space>
            <a-form-item no-style>
              <a-space>
                <a-button class="w-40" type="default" @click="editItem">
                  <template #icon>
                    <EditOutlined />
                  </template>
                  编辑商品
                </a-button>
                <a-button
                  class="w-40"
                  danger
                  type="default"
                  @click="removeSelectItem"
                >
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                  移除商品
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </div>
      <Modals />
    </a-spin>
    <AiTitle
      v-model="aiTitleBoxState"
      :image="selectImage"
      @ok="getSelectAiTitle"
    />
  </div>
</template>
